package com.tzy.spi.aop.Interceptor;

import com.tzy.spi.aop.JoinPoint;
import com.tzy.spi.aop.annotition.CustomAnno;
import com.tzy.spi.aop.annotition.Returning;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class AfterReturningMethodInterceptor extends AbstractMethodInterceptor {



    @Override
    public Object toDo(JoinPoint joinPoint) throws Throwable{


        Object returnObj = joinPoint.invoke();

        Method method = getMethod();

            try {
                method.invoke(getAspect(), buildParam(method,joinPoint,returnObj));
            } catch (IllegalAccessException | InvocationTargetException ex) {
                ex.printStackTrace();
            }

        return returnObj;
    }


    public Object[] buildParam(Method method,JoinPoint joinPoint,Object returnObj){
        List<Object> objects =new ArrayList<>();


        if (method.getParameterCount()==0) {
            return objects.toArray();
        }

        for (Parameter parameter : method.getParameters()) {

            if(parameter.getAnnotation(CustomAnno.class)!=null){
                objects.add(joinPoint.annotation());
            } else if (parameter.getAnnotation(Returning.class)!=null) {
                objects.add(returnObj);
            } else {
                objects.add(null);
            }
        }

        return objects.toArray();

    }


}
